//
//  MassageViewController.m
//  runingBabyModel
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MassageViewController.h"
#import "MassageTableViewCell.h"
#import "Massage.h"
#import "UIImageView+WebCache.h"
#import "RequestData.h"
#import "MassageDetailViewController.h"

#import "UIView+MJExtension.h"
#import "MJRefresh.h"
@interface MassageViewController ()<UITableViewDataSource , UITableViewDelegate , RequestFinishDelegate>

@property (nonatomic , strong) UITableView *recommendView;
@property (nonatomic , strong) UITableView *radioView;
@property (nonatomic , strong) UITableView *howDoView;

@property (nonatomic , strong) NSMutableArray *massageArray;

@property (nonatomic , strong) NSString *url;

//@property (nonatomic , strong) UISegmentedControl *segmented;


@end

@implementation MassageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发现";
    
    // 初始化数组接收数据
    self.massageArray = [NSMutableArray array];
    //布局 SegmentedControl
    [self layoutSegmentedControl];
    //布局页面
    [self layoutRecommendView];
    [self refreshView:@"1" duedate:@"1460217600"];
    [self loadMoreView:@"1" duedate:@"1460217600"];
    self.navigationController.navigationBar.barTintColor =[UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
}

#pragma mark - 布局 -
//布局页面
- (void)layoutRecommendView{
    self.recommendView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height / 18 + 65, self.view.frame.size.width, self.view.frame.size.height - self.view.frame.size.height / 18 -  65 - 4) ];
    _recommendView.backgroundColor = [UIColor colorWithRed:255/256.0 green:204/256.0 blue:204/256.0 alpha:1];
    self.recommendView.delegate = self;
    self.recommendView.dataSource = self;
    [self.view addSubview:_recommendView];
}
//布局 SegmentedControl
- (void)layoutSegmentedControl{
    //创建对象
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"推荐",@"视频",@"怎么办"]];
    //配置属性
    segment.backgroundColor = [UIColor whiteColor];
    segment.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height / 18);
    //设置选中的分段
    segment.selectedSegmentIndex = 0;
    //设置选中的颜色
    segment.tintColor = [UIColor colorWithRed:255 / 256.0 green:204 / 256.0 blue:204 / 256.0 alpha:1];
    //请求数据
    [self requestDataWithParameter:@"1" duedate:@"1460217600"];
    //添加时间
    [segment addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segment];
}

#pragma mark - 数据请求 -
- (void)requestDataWithParameter:(NSString *)parameter duedate:(NSString *)duedate{
    //http://api.addinghome.com/adco/v2/getContentList?channelId=1&ci=%E5%8C%97%E4%BA%AC%E5%B8%82&contentId=1&duedate=1460217600&pr=%E5%8C%97%E4%BA%AC%E5%B8%82&size=12&start=0&userStatus=1
    //http://api.addinghome.com/adco/v2/getContentList?userStatus=1&duedate=0&channelId=6&start=0&size=30&pr=%E5%8C%97%E4%BA%AC%E5%B8%82&ci=%E5%8C%97%E4%BA%AC%E5%B8%82
    RequestData *req = [[RequestData alloc]init];
    //拼接参数
    NSString *ci = @"%E5%8C%97%E4%BA%AC%E5%B8%82";
    NSString *pr = @"%E5%8C%97%E4%BA%AC%E5%B8%82";
    NSString *urlStr = [NSString stringWithFormat:@"http://api.addinghome.com/adco/v2/getContentList?channelId=%@&ci=%@&contentId=1&duedate=%@&pr=%@&size=12&start=0&userStatus=1",parameter,ci,duedate,pr];
    [req requestWithUrl:urlStr andDelegate:self];
}

//http://api.addinghome.com/adco/v2/getContentList?channelId=1&ci=%E5%8C%97%E4%BA%AC%E5%B8%82&contentId=1&duedate=1460217600&pr=%E5%8C%97%E4%BA%AC%E5%B8%82&size=12&start=0&userStatus=1
//http://api.addinghome.com/adco/v2/getContentList?channelId=1&ci=%E5%8C%97%E4%BA%AC%E5%B8%82&contentId=1&duedate=1460217600&pr=%E5%8C%97%E4%BA%AC%E5%B8%82&size=12&start=0&userStatus=1
//http://api.addinghome.com/adco/v2/getContentList?channelId=1&ci=%E5%8C%97%E4%BA%AC%E5%B8%82&contentId=1&duedate=%E5%8C%97%E4%BA%AC%E5%B8%82&pr=1460217600&size=12&start=0&userStatus=1
- (void)requestSuccess:(NSData *)data{
    [self.massageArray removeAllObjects];
    //解析
    NSArray *massArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    //封装
    for (NSDictionary *massDic in massArray) {
        if([massDic objectForKey:@"id"]){
        
            Massage *massage = [[Massage alloc]init];
            NSArray *array = [massDic valueForKey:@"images"];
            massage.nickName = [massDic objectForKey:@"mediaName"];
            massage.title = [massDic objectForKey:@"title"];
            massage.imageUrl = (NSString *)array.firstObject;
            massage.oUrl = [massDic objectForKey:@"ourl"];
            [self.massageArray addObject:massage];
        }
    }
    [self.recommendView reloadData];
}
- (void)requestError:(NSError *)error{
    NSLog(@"error:%@",error);
}

#pragma mark - 刷新 -
//下拉刷新
- (void)refreshView:(NSString *)parameter duedate:(NSString *)duedate
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.recommendView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestDataWithParameter:parameter duedate:duedate];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.recommendView.header endRefreshing];
    }];
    // 马上进入刷新状态
    [self.recommendView.header beginRefreshing];
}
//上拉刷新
- (void)loadMoreView:(NSString *)parameter duedate:(NSString *)duedate
{
    RequestData *req = [[RequestData alloc]init];
    __block int i = 0;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.recommendView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        ++i;
        if(i > 5){
            [self finishLoad];
            return ;
        }
        NSString *ci = @"%E5%8C%97%E4%BA%AC%E5%B8%82";
        NSString *pr = @"%E5%8C%97%E4%BA%AC%E5%B8%82";
        NSString *urlStr = [NSString stringWithFormat:@"http://api.addinghome.com/adco/v2/getContentList?channelId=%@&ci=%@&contentId=1&duedate=%@&pr=%@&size=%d&start=0&userStatus=1",parameter,ci,duedate,pr,(i + 1) * 12];
        [req requestWithUrl:urlStr andDelegate:self];
        // 拿到当前的上拉刷新控件，结束刷新状态
        [self.recommendView.footer endRefreshing];
    }];
}
//加载最后一份数据
- (void)finishLoad
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadLastData方法）
    self.recommendView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
}
- (void)loadLastData{
    [self.recommendView.footer noticeNoMoreData];
}
#pragma mark - segmented点击事件处理 -
- (void)segmentedAction:(UISegmentedControl *)segmented{
    if(segmented.selectedSegmentIndex == 0){
        //推荐页面
        [self requestDataWithParameter:@"1" duedate:@"1460217600"];
        [self refreshView:@"1" duedate:@"1460217600"];
        [self loadMoreView:@"1" duedate:@"1460217600"];
    }else if(segmented.selectedSegmentIndex == 1){
        //视频页面
        [self requestDataWithParameter:@"4" duedate:@"1460217600"];
        [self refreshView:@"4" duedate:@"1460217600"];
        [self loadMoreView:@"4" duedate:@"1460217600"];
    }else if(segmented.selectedSegmentIndex == 2){
        //怎么办页面
        [self requestDataWithParameter:@"6" duedate:@"0"];
        [self refreshView:@"6" duedate:@"0"];
        [self loadMoreView:@"6" duedate:@"0"];
    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate的代理方法 -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.massageArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MassageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[MassageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    Massage *massage = [self.massageArray objectAtIndex:indexPath.row];
    cell.massage = massage;
    
    [cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:massage.imageUrl] placeholderImage:[UIImage imageNamed:@"picholder.png"]];
//    NSLog(@"%@",NSHomeDirectory());
    cell.backgroundColor = [UIColor colorWithRed:255/256.0 green:204 / 256.0 blue:204/256.0 alpha:1];
    return cell;
}

#pragma mark - 跳转到详情页面 -
//点击cell跳转到详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MassageDetailViewController *massageDetailVC = [[MassageDetailViewController alloc]init];
    UINavigationController *massageNVC = [[UINavigationController alloc] initWithRootViewController:massageDetailVC];
    Massage *massage = [self.massageArray objectAtIndex:indexPath.row];
    massageDetailVC.htmlUrl = massage.oUrl;
    [self presentViewController:massageNVC animated:YES completion:nil];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
